package com.dcjt.firehotcarpad.base

import android.app.Activity
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.content.pm.ActivityInfo
import android.location.Location
import android.os.Bundle
import android.view.animation.BounceInterpolator
import android.widget.ImageView
import androidx.multidex.MultiDex
import com.amap.api.maps.model.LatLng
import com.amap.api.navi.model.AMapNaviPathGroup
import com.aries.library.fast.FastConfig
import com.aries.library.fast.manager.LoggerManager
import com.aries.library.fast.retrofit.FastRetrofit
import com.aries.library.fast.util.SizeUtil
import com.aries.library.fast.util.ToastUtil
import com.dcjt.firehotcarpad.R
import com.dcjt.firehotcarpad.moudle.HandleDisasterActivity
import com.dcjt.firehotcarpad.retrofit1.TokenInvalidInterceptor
import com.dcjt.firehotcarpad.utils.CrashHandler
import com.juntu.loginlib.contact.LoginUrl
import com.yhao.floatwindow.FloatWindow
import com.yhao.floatwindow.MoveType
import com.yhao.floatwindow.Screen
import org.simple.eventbus.EventBus


class App : Application() {
    companion object {
        var INSTANCE: App? = null
        var address: String? = null//当前的位置名字

        @JvmField
        var isLeader: Boolean = false//这个临时使用变量  方便测试

        //当前的位置
        var currentPosition: Location? = null

        //车辆调派位置
        var carPoint: LatLng? = null

        //灾情位置
        var disPoint: LatLng? = null

        //用于导航路径的存放
        var navPathGroup: AMapNaviPathGroup? = null

        @JvmStatic
        fun getAppProcessName(context: Context): String {
            //当前应用pid
            val pid = android.os.Process.myPid()
            //任务管理类
            val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            //遍历所有应用
            for (info in manager.runningAppProcesses) {
                if (info.pid == pid)
                //得到当前应用
                    return info.processName//返回包名
            }
            return ""
        }


        @JvmStatic
        fun get() = INSTANCE

    }

    private var activityAount = 0


    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }

    override fun onCreate() {
        super.onCreate()
        registerActivityLifecycleCallbacks(activityLifecycleCallbacks);
        INSTANCE = this
        ToastUtil.init(this)
        LoggerManager.init("FireHotCarPadRepository========")
        LoginUrl.setLoginUrl(ApiPath.BASE_HTTP+ApiPath.BASE_PORT)

        //日志
        val crashHandler = CrashHandler.getInstance()
        crashHandler.init(this)
        //初始化Retrofit配置
        FastRetrofit.getOkHttpClientBuilder()
            .addInterceptor(TokenInvalidInterceptor())

        FastRetrofit.getInstance()
            .setBaseUrl(ApiPath.BASE_URL)
            .trustAllSSL()//信任所有证书--也可设置useSingleSignedSSL(单向认证)或useBothSignedSSL(双向验证)
//            .setHeaders(headerMaps)//设置统一请求头
            .setLogEnable(true)//设置请求全局log-可设置tag及Level类型
            //                .setLogEnable(BuildConfig.DEBUG, TAG, HttpLoggingInterceptor.Level.BASIC)
            .setTimeout(30)//设置统一超时--也可单独调用read/write/connect超时(可以设置时间单位TimeUnit)

//        val impl = AppImpl(this)
        //推荐先获取library里默认TitleBarView配置再按需修改的模式 FastTitleConfigEntity
        val titleConfig = FastConfig.getInstance(this).titleConfig
        val quitConfigEntity = FastConfig.getInstance(this).quitConfig
        FastConfig.getInstance(this)
            // 其它属性请查看getInstance默认设置
            .setTitleConfig(
                titleConfig
                    //设置TitleBarView 所有TextView颜色
                    .setTitleTextColor(this.resources.getColor(R.color.write))
                    //设置TitleBarView背景资源
                    .setTitleBackgroundResource(R.color.titleBg)
                    //设置是否状态栏浅色模式(深色状态栏文字及图标)
                    .setLightStatusBarEnable(false)
                    .setDividerHeight(0)
                    .setLeftTextDrawable(R.drawable.icon_back)
                    //设置TitleBarView海拔高度
                    .setTitleElevation(0f)
            )
            .setQuitConfig(
                quitConfigEntity
                    .setQuitDelay(2000)
                    .setBackToTaskDelayEnable(false)
            )
//          .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
            .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
            //设置Glide背景色
            .setPlaceholderColor(resources.getColor(R.color.colorPlaceholder))
            //设置Glide圆角背景弧度
            .setPlaceholderRoundRadius(SizeUtil.dp2px(2f).toFloat())
            .setSwipeBackEnable(false, INSTANCE)
//            .setLoadMoreFoot(impl)
//            .setLoadingDialog(impl)
//            .setMultiStatusView(impl)
//            .setHttpErrorControl(impl).defaultRefreshHeader = impl

        val imageView = ImageView(applicationContext)
        imageView.setImageResource(R.drawable.ic_document_add)

        FloatWindow
            .with(applicationContext)
            .setView(imageView)
            .setFilter(true, HandleDisasterActivity::class.java)
            .setWidth(100)                               //设置控件宽高
            .setHeight(Screen.width, 0.2f)
            .setX(0)                                   //设置控件初始位置
            .setY(Screen.height, 0.5f)
            .setDesktopShow(false)                        //桌面显示
            .setMoveType(MoveType.slide)
            .setMoveStyle(500, BounceInterpolator())  //贴边动画时长为500ms，加速插值器
            .build()
    }


    /**
     * Activity 生命周期监听，用于监控app前后台状态切换
     */
    var activityLifecycleCallbacks: ActivityLifecycleCallbacks =
        object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(
                activity: Activity?,
                savedInstanceState: Bundle?
            ) {
            }

            override fun onActivityStarted(activity: Activity?) {
                if (activityAount == 0) {
                    //app回到前台
//                isForeground = true;
                    EventBus.getDefault().post(true, "isForeground")

                }
                activityAount++
            }

            override fun onActivityResumed(activity: Activity?) {}
            override fun onActivityPaused(activity: Activity?) {}
            override fun onActivityStopped(activity: Activity?) {
                activityAount--
                if (activityAount == 0) {
                    //app 回到后台
//                    isForeground = false
                    //关闭录音 关闭dialog
                    EventBus.getDefault().post(false, "isForeground")

                }
            }

            override fun onActivitySaveInstanceState(
                activity: Activity?,
                outState: Bundle?
            ) {
            }

            override fun onActivityDestroyed(activity: Activity?) {}
        }

}